<template>
  <div class="container">
    <van-nav-bar
      :title="userInfo.regStatus == 4 ? '资料修改' : '商户入网'"
      right-text="保存"
      left-arrow
      @click-left="goBack"
      @click-right="noSave"
    />
    <div class="content-box">
      <Remarks v-if="userInfo.regStatus == 4" :contents="userInfo.remarks" />
      <!-- 步骤条 -->
      <Steps
        :dataSource="[
          { name: '基本信息', checked: true },
          { name: '结算信息', checked: true },
          { name: '费率信息', checked: true },
          { name: '附件信息' },
        ]"
      />
      <!-- 主体 -->
      <van-form
        scroll-to-error
        input-align="right"
        ref="form"
        @submit="nextStep"
      >
        <van-field
          v-if="configEle.includes('eleCardEquip') && formData.payType == 2"
          v-model="formData.equipmentSN"
          class="mt-margin"
          label="刷卡设备"
          placeholder="请输入刷卡终端SN编号"
          @input="equipmentInput"
          :rules="rules"
        >
          <template #button>
            <van-icon name="scan" size="20px" @click="noScan" />
          </template>
        </van-field>
        <van-field
          v-model="formData.rate_sk"
          v-if="
            configEle.includes('eleCardRate') &&
            merchant.sk_allowShow == 1 &&
            formData.payType == 2
          "
          :disabled="true"
          label="刷卡费率%"
          placeholder="请输入刷卡结算费率"
          type="number"
          @input="rateSkInput"
        />
        <van-field
          v-model="formData.rate_fd"
          v-if="
            configEle.includes('eleCardLimit') && merchant.fd_allowShow == 1
          "
          :disabled="true"
          label="刷卡封顶"
          placeholder="请输入借记卡刷卡封顶值"
          type="number"
          @input="rateFdInput"
        />
        <!-- 刷卡文案 -->
        <div
          v-if="configEle.includes('eleCardDesc') && formData.payType == 2"
          class="notes"
        >
          {{ eleCardDesc.eleDefaultValue || "" }}
        </div>
        <div
          class="posLayout"
          v-if="configEle.includes('eleScanRate') && merchant.sm_allowShow == 1"
        >
          <van-field
            class="mt-margin"
            v-model="formData.rate_sm"
            :disabled="true"
            label="扫码费率%"
            placeholder="请输入扫码结算费率"
            type="number"
            @input="rateSmInput"
          />
        </div>

        <div
          class="posLayout"
          v-if="configEle.includes('eleD0Rate') && merchant.d0_allowShow == 1"
        >
          <van-field
            v-model="formData.rate_d0"
            :disabled="true"
            class="mt-margin"
            label="D0增量费率%"
            placeholder="请输入D0增量费率"
            type="string"
          />
        </div>

        <div
          class="posLayout"
          v-if="configEle.includes('eleD1Rate') && merchant.d1_allowShow == 1"
        >
          <van-field
            v-model="formData.rate_d1"
            :disabled="true"
            class="mt-margin"
            label="D1增量费率%"
            placeholder="请输入D1增量费率"
            type="number"
            @input="rateD1Input"
          />
        </div>
        <!-- 
        <p style="font-size:14px; padding:35px 20px 20px 20px">结算周期增量费率说明：</p>
        <p
          style="font-size:14px; padding:0px 20px 20px 20px; line-height:25px;"
        >结算周期D0，每天的交易额将额外收取D0增量手续费；开启成功后自然日的交易当日到账。</p>
        <p
          style="font-size:14px; padding:0px 20px 20px 20px; line-height:25px;"
        >结算周期D1，周六日的交易金额将额外收取D1增量手续费；开启成功后自然日的交易第二天到账。</p>-->
        <div v-if="configEle.includes('eleRateDesc')" class="notes">
          {{ eleRateDesc.eleDefaultValue || "" }}
        </div>
        <van-button
          block
          type="info"
          color="#FFB72F"
          class="next-step-btn"
          native-type="submit"
          >下一步</van-button
        >
      </van-form>
    </div>
  </div>
</template>

<script>
import { getEquipSn } from "@/api/stores.js";
import { save } from "@/api/stores";
import { getWxBusiness } from "@/api/mreinfo";

export default {
  name: "Step3",
  components: {
    HeaderComp: () => import("@/components/HeaderComps"),
    Remarks: () => import("@/components/Remarks"),
    Steps: () => import("@/components/steps"),
  },
  data() {
    return {
      SNMessage: "",
      show1: false,
      show2: false,
      formData: {
        payType: "",
        payTypeText: "",
        firstSettleType: "",
        firstSettleTypeText: "",
        equipmentSN: "",
        rate_sk: "",
        rate_fd: "",
        rate_sm: "",
        rate_d0: "",
        rate_d1: "",
        // rate_ds: "",
        // rate_wx: "",
      },
      rules: [
        {
          pattern: /^[0-9a-zA-Z]{0,50}$/,
          message: "只支持数字和字母的格式",
          trigger: "onChange",
        },
        {
          validator: this.asyncValidator,
          message: "设备不存在",
          trigger: "onBlur",
        },
      ],
      showRateWx: false,
      isMccFixedRate: false,
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
    agentInfo() {
      return this.$store.state.user.agentInfo;
    },
    merchant() {
      return this.$store.state.merchant;
    },
    pass() {
      return this.$store.getters.valid_step3;
    },
    Autonomy() {
      return this.$store.state.common.Autonomy;
    },
    isSurportCrad() {
      // 判断是否支持刷卡，并置灰disabled
      const { supportTradeType } = this.$store.state.user.channelInfo || "";
      const xwStatus = this.$store.state.user.agentInfo.xwStatus;
      return [2, 3].includes(supportTradeType) && xwStatus === 1;
    },
    firstSettleTypeList() {
      // 当刷卡的时候，过滤D0
      return this.firstSettleTypeListData.map((item) => {
        return {
          ...item,
          disabled: Number(this.formData.payType) === 2 && item.value === 1,
        };
      });
    },
    rateSmRules() {
      // const validator = (val) => {
      //   return val >= this.merchant.rate_sm_minValue &&
      //   val <= this.merchant.rate_sm_maxValue
      // }
      const max = Number(
        !this.showRateWx
          ? this.merchant.rate_sm_maxValue
          : this.merchant.rate_wx_maxValue
      );
      const min = Number(
        !this.showRateWx
          ? this.merchant.rate_sm_minValue
          : this.merchant.rate_wx_minValue
      );
      const rules = [
        {
          validator: (val) => val >= min && val <= max,
          message: `请输入${min}-${max}的扫码费率`,
          trigger: "onChange",
        },
        {
          pattern: /^(\d+|\d+\.\d{1,2})$/,
          message: "只能输入两位小数哦！",
          trigger: "onChange",
        },
      ];
      return this.isMccFixedRate ? [] : rules;
    },
    configEle() {
      return this.$store.state.common.config.map((item) => item.configEle);
    },
    eleRateDesc() {
      const item = this.$store.state.common.config.find(
        (item) => item.configEle === "eleRateDesc"
      );
      return item;
    },
    eleCardDesc() {
      const item = this.$store.state.common.config.find(
        (item) => item.configEle === "eleCardDesc"
      );
      return item;
    },
  },
  mounted() {
    // 获取代理的商户默认费率
    const list = this.agentInfo.agentDefaultMerchantRates;
    if (list.length) {
      const rateSk = list.find((item) => item.rateType === 2);
      const rateSM = list.find((item) => item.rateType === 1);
      const rate_sk_value =
        rateSk?.rateValue || this.merchant.rate_sk_defaultValue;
      const rate_sm_value =
        rateSM?.rateValue || this.merchant.rate_sm_defaultValue;

      this.merchant.rate_sk_defaultValue = Number(rate_sk_value);
      this.merchant.rate_sm_defaultValue = Number(rate_sm_value);
    }
    let form = this.$store.state.merchant;
    let newform = JSON.parse(JSON.stringify(form));
    this.formData = newform;
    const rateList = [
      "rate_fd",
      "rate_sk",
      "rate_sm",
      "rate_d0",
      "rate_d1",
      // "rate_ds",
      // "rate_wx",
    ];
    rateList.forEach((item) => {
      const value =
        Number(this.merchant[item]) ||
        Number(this.merchant[item + "_defaultValue"]) ||
        Number(this.merchant[item + "_minValue"]);
      console.log(
        item,
        Number(this.merchant[item]),
        Number(this.merchant[item + "_defaultValue"]),
        Number(this.merchant[item + "_minValue"])
      );
      this.formData[item] = value;
      const key = `set${item.replace("r", "R")}`;
      this.$store.commit(key, value);
    });

    window.scrollTo({
      left: 0,
      top: 0,
      behavior: "smooth",
    });
    window.AndroidInfo = this.AndroidInfo;
    // this.$nextTick(() => {
    //   this.isShowRateWx();
    // });
  },
  // watch: {
  //   "formData.firstSettleType": function (val) {
  //     if (val) {
  //       const item = this.agentInfo.agentSettleList.find(
  //         (item) => Number(item.settleType) === val
  //       );
  //       this.$store.commit("setChannelCode", item.channelCode);
  //     }
  //   },
  //   "formData.payType": function (val) {
  //     if (val == 1) {
  //       this.$store.commit("setRate_fd", this.merchant.rate_fd_defaultValue);
  //       this.$store.commit("setRate_sk", this.merchant.rate_sk_defaultValue);
  //     }
  //     // 当选择了支付方式，且结算周期长度为1时，自动填充
  //     if (val && this.firstSettleTypeList.length === 1) {
  //       this.firstSettleType = this.firstSettleTypeList[0].value;
  //       this.$store.commit("firstSettleType", this.firstSettleTypeList[0]);
  //     }
  //   },
  // },
  created() {
    this.$store.dispatch("getSystemRates");
    this.$store.dispatch("getUperAgentRates", this.agentInfo.id);
  },
  methods: {
    AndroidInfo(data) {
      this.formData.equipmentSN = data;
      this.$refs.form.validate();
    },
    noScan() {
      var that = this;
      var u = navigator.userAgent;
      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if (isAndroid) {
        injectedObject.UseScan();
      }
      if (isiOS) {
        function setupWebViewJavascriptBridge(callback) {
          if (window.WebViewJavascriptBridge) {
            return callback(WebViewJavascriptBridge);
          }
          if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
          }
          window.WVJBCallbacks = [callback]; // 创建一个 WVJBCallbacks 全局属性数组，并将 callback 插入到数组中。
          var WVJBIframe = document.createElement("iframe"); // 创建一个 iframe 元素
          WVJBIframe.style.display = "none"; // 不显示
          WVJBIframe.src = "wvjbscheme://__BRIDGE_LOADED__"; // 设置 iframe 的 src 属性
          document.documentElement.appendChild(WVJBIframe); // 把 iframe 添加到当前文导航上。
          setTimeout(function () {
            document.documentElement.removeChild(WVJBIframe);
          }, 0);
        }
        // 这里主要是注册 OC 将要调用的 JS 方法。
        setupWebViewJavascriptBridge(function (bridge) {
          bridge.callHandler(
            "UseScan",
            { data: "UseScan" },
            function (dataFromOC) {
              document.getElementById("returnValue").value = dataFromOC;
            }
          );
          bridge.registerHandler(
            "iosSendSNCode",
            function (data, responseCallback) {
              // 回调app
              that.formData.equipmentSN = data;
              that.$refs.form.validate();
              responseCallback(responseData);
            }
          );
        });
      }
    },
    // 保存
    noSave() {
      this.$dialog
        .confirm({
          title: "商户认证",
          message: `确认是否保存资料？`,
          cancelButtonText: "取消",
          // cancelButtonColor: "#FFB72F",
          confirmButtonText: "确认",
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          // 保存资料
          if (this.formData.openType) {
            this.$store.commit("setComplete", 0);
            this.$toast({
              type: "loading",
              message: "正在提交...",
              forbidClick: true,
              duration: 0,
            });
            save(this.$store.state)
              .then((res) => {
                // document.title = "提交成功";
                this.$toast.clear();
                if (res.code == 200) {
                  this.$toast({
                    type: "success",
                    message: "保存成功",
                    duration: 1500,
                  });
                  this.$store.dispatch("setSaved", true);
                } else {
                  this.$toast({
                    message: res.msg || "操作失败",
                    duration: 2000,
                    forbidClick: true,
                  });
                }
              })
              .catch((err) => {
                this.$toast.clear();
                // document.title = "返回APP";
              });
            // next();
          } else {
            document.title = "返回APP";
          }
        })
        .catch(() => {
          // 取消
          // document.title = "返回APP";
          // next();
        });
    },
    asyncValidator(val) {
      // let userInfo = this.userInfo.agentId;
      const agenId = this.userInfo.agentId || this.agentInfo.id;
      console.log(agenId, this.userInfo.agentId, this.agentInfo.id);
      if (/^[0-9a-zA-Z]{0,50}$/.test(val)) {
        return new Promise((resolve, reject) => {
          getEquipSn({ agenId, equipSN: val })
            .then((res) => {
              if (res.code == 200) {
                const { data } = res;
                const { currAgent, payEquip, bind } = data;
                // 判断，任意一个条件不符合就提示错误
                if (!(currAgent && payEquip && bind)) {
                  this.$store.commit("setEquipmentSN", "");
                  const message = {
                    currAgent: "非当前代理设备",
                    payEquip: "请输入未绑定的刷卡终端SN",
                    bind: "该设备已绑定",
                  };
                  // 获取提示文案
                  this.rules[1].message = !currAgent
                    ? message.currAgent
                    : !payEquip
                    ? message.payEquip
                    : !bind
                    ? message.bind
                    : "";
                  resolve(false);
                } else {
                  resolve(true);
                  this.$store.commit("setEquipmentSN", val);
                }
              } else {
                this.rules[1].message = res.msg;
                this.$store.commit("setEquipmentSN", "");
                resolve(false);
              }
            })
            .catch((err) => {
              console.log(err, "err");
              this.rules[1].message = "校验失败";
              this.$store.commit("setEquipmentSN", "");
              resolve(false);
            });
        });
      }
    },
    equipmentInput(val) {
      // this.$store.commit("setEquipmentSN", val);
    },
    rateSkInput(val) {
      this.$store.commit("setRate_sk", val);
    },
    rateFdInput(val) {
      this.$store.commit("setRate_fd", val);
    },
    rateSmInput(val) {
      this.$store.commit("setRate_sm", val);
    },
    rateD0Input(val) {
      this.$store.commit("setRate_d0", val);
    },
    rateD1Input(val) {
      this.$store.commit("setRate_d1", val);
    },
    // rateDsInput(val) {
    //   this.$store.commit("setRate_ds", val);
    // },
    rateWxInput(val) {
      this.$store.commit("setRate_wx", val);
    },
    valid_sk(val) {
      const max = Number(this.merchant.rate_sk_maxValue);
      const min = Number(this.merchant.rate_sk_minValue);
      return val >= min && val <= max;
    },
    valid_fd(val) {
      const max = Number(this.merchant.rate_fd_maxValue);
      const min = Number(this.merchant.rate_fd_minValue);
      return val >= min && val <= max;
    },
    valid_sm(val) {
      const max = Number(this.merchant.rate_sm_maxValue);
      const min = Number(this.merchant.rate_sm_minValue);
      return val >= min && val <= max;
    },
    valid_wx(val) {
      return (
        val >= this.merchant.rate_wx_minValue &&
        val <= this.merchant.rate_wx_maxValue
      );
    },
    valid_d0(val) {
      const max = Number(this.merchant.rate_d0_maxValue);
      const min = Number(this.merchant.rate_d0_minValue);
      return val >= min && val <= max;
    },
    valid_d1(val) {
      const max = Number(this.merchant.rate_d1_maxValue);
      const min = Number(this.merchant.rate_d1_minValue);
      return val >= min && val <= max;
    },
    // valid_ds(val) {
    //   const max = Number(this.merchant.rate_ds_maxValue);
    //   const min = Number(this.merchant.rate_ds_minValue);
    //   return val >= min && val <= max;
    // },
    goBack() {
      this.$router.push({
        path: "/submitInfo/step3",
      });
    },
    selectPayType(data, index) {
      this.formData.payTypeText = data.text;
      this.formData.payType = data.value;
      this.$store.commit("setPayType", data);
      if (data.value == 1) {
        this.$store.commit("setEquipmentSN", "");
      }
      const settle = Number(this.formData.firstSettleType);
      const firstSettleTypeList = this.firstSettleTypeList.filter(
        (item) => !item.disabled
      );
      const settleList = firstSettleTypeList.map((item) => item.value);
      if (!settleList.includes(settle)) {
        this.formData.firstSettleType = settleList[0];
        this.formData.firstSettleTypeText = firstSettleTypeList[0].text;
        this.$store.commit("firstSettleType", firstSettleTypeList[0]);
      }
      this.show1 = false;
    },
    firstSettleTypes(data, index) {
      this.formData.firstSettleTypeText = data.text;
      this.formData.firstSettleType = data.value;
      this.$store.commit("firstSettleType", data);
      this.show2 = false;
      console.log(this.formData.rate_d0, "this.formData.rate_d0");
    },
    nextStep() {
      this.$router.push({
        path: "/submitInfo/step5",
      });
    },

    // 是否展示微信扫码费率
    isShowRateWx() {
      const row = this.merchant;
      const settle = this.firstSettleTypeListData.find(
        (item) => item.value === 3
      );
      const checkfirstSettleType = row.firstSettleType === 3;
      // 代理商的结算渠道进且仅有一个，而且是wx的渠道
      const checkSettle =
        settle && settle.value === 3 && settle.channelCode === "WX";
      console.log(
        checkSettle,
        checkfirstSettleType,
        row,
        settle,
        this.firstSettleTypeListData,
        "isShowRateWx"
      );
      if (checkSettle && checkfirstSettleType) {
        this.formData.rate_sm = this.merchant.rate_wx_defaultValue;
        const req = {
          merType: "0" + row.merchantType,
          mccCode: row.mcc,
        };
        this.showRateWx = true;
        getWxBusiness(req).then((res) => {
          console.log(res);
          const { data, code } = res;
          if (code === 200 && !data.isDiscount) {
            this.formData.rate_sm = data.fixedRate;
            this.isMccFixedRate = true;
          }
        });
      }
    },
  },
};
</script>
<style scoped lang="less">
/deep/.van-picker-column__item--selected {
  color: #ff9600 !important;
}
/deep/.van-picker__confirm {
  color: #ff9600 !important;
}
/deep/.van-field__label {
  color: #323233;
}
/deep/.van-dialog__content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 57px 0;
}
.next-step-btn {
  width: 80%;
  margin: 100px auto;
}
.container {
  overflow: hidden;
}
.content-box {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}

.mt-margin {
  margin-top: 24px;
}
.example-img {
  width: 420px;
  height: 270px;
}

// .header-box {
//   display: flex;
//   align-items: center;
//   justify-content: space-between;
//   padding: 32px;
//   border-bottom: 1px solid #d7d7d7;
//   font-size: 36px;
//   background: #fff;
//   position: fixed;
//   left: 0;
//   right: 0;
//   top: 0;
//   z-index: 99;
//   .header-item {
//     font-weight: 500;
//     color: #131313;
//   }
//   .header-save {
//     color: #ffb72f;
//     font-size: 28px;
//   }
// }
.notes {
  font-size: 28px;
  font-weight: 400;
  color: #131313;
  opacity: 0.8;
  padding: 24px 31px 0;
  line-height: 50px;
  white-space: pre-wrap;
}
/deep/ .van-field__button {
  display: flex;
  align-items: center;
}
.posLayout {
  position: relative;
}
.posRight {
  position: absolute;
  right: 20px;
  top: 7px;
  color: #323233;
  font-size: 14px;
}
.black {
  color: #323233;
}
.gray {
  color: #c8c9cc;
}
/deep/.van-nav-bar__title {
  font-size: 36px !important;
}
/deep/ .van-nav-bar__text {
  color: #ffb72f !important;
}
/deep/ .van-nav-bar__content {
  height: 110px !important;
}
</style>
